# coding: utf-8

import os, re

from django.contrib.auth.decorators import login_required
from django.http import HttpResponse
from django.shortcuts import render_to_response
from django.template import RequestContext as Context

from filebrowser.settings import *
from filebrowser.views import filebrowser_post_upload
from filebrowser.base import FileObject

from functions import post_upload_callback, get_data_object
from models import *

@login_required
def sync (request, force=False):
    """
    Syncs all FileData objects with 
    current state of filebrowser directory
    """
    # Precompile regular expressions
    filter_re = []
    for exp in EXCLUDE:
       filter_re.append(re.compile(exp))
    for k,v in VERSIONS.iteritems():
        exp = (r'_%s.(%s)') % (k, '|'.join(EXTENSION_LIST))
        filter_re.append(re.compile(exp))
    
    path = os.path.join(MEDIA_ROOT, DIRECTORY)
    
    file_list = []
    
    # walkt throu the filebrowser directory 
    # and make the medman.functions.post_upload_callback()
    # for all/new files (except file versions and excludes)
    for dirpath,dirnames,filenames in os.walk(path):
        for filename in filenames:
            # no "hidden" files
            filtered = filename.startswith('.')
            if filtered:
                continue
            for re_prefix in filter_re:
                if re_prefix.search(filename):
                    filtered = True
            if filtered:
                continue
            path = os.path.join(dirpath, filename)
            rel_path = path.replace(MEDIA_ROOT, "")
            if rel_path.startswith("/"):
                rel_path = rel_path[1:]
            current_file = FileObject(rel_path)
            file_data_object = get_data_object(current_file)
            if force or (file_data_object.count() == 0):
                post_upload_callback(sender=request, path='', file=current_file)
                file_list.append(current_file)
    
    return render_to_response('medman/sync.html', {
        "file_list": file_list,
        "force": force
    }, context_instance=Context(request))

def sync_all(request):
    """
    Syncs with current state of filebrowser directory.
    Creates FileData of new files
    """
    return sync(request, True)